<?php
namespace App\Utilitys;

use Illuminate\Support\Facades\Storage;

class Upload
{
    //上传工具类

    /**
     * 上传图片到本地，返回地址
     * @return string
     */
    public static function uploadImg($request, $imgName = 'img')
    {
        $uploadSizeLimit = 10 * 1024 * 1023; //限制上传文件尺寸10M
        $suffix_img = [ //允许后缀
            "png", "jpg", "gif", "bmp", "jpeg", "jpe",
        ];
        if (!$request->hasFile($imgName)) { return ''; }
        //判断文件存在
        if ($_FILES[$imgName]['size'] > $uploadSizeLimit) {
            //echo "<script>alert('图片过大！');history.go(-1);</script>";exit;
            return array('code'=>-2,'msg'=>'文件尺寸过大');
        }
        $file = $request->file($imgName);
        $data['fileSize'] = $file->getClientSize();
        if ($data['fileSize'] > $uploadSizeLimit) {
            return false;
        }
        $fileExt = $file->getClientOriginalExtension();
        $fileExt = strtolower($fileExt);
        if ($fileExt && !in_array($fileExt, $suffix_img)) {
            return array('code'=>-2,'msg'=>'文件类型不合法');
        }
        if(!$file->isValid()){
            return array('code'=>-2,'msg'=>'文件错误');
        }
        $extension = $fileExt ?: 'png';
        $folderName = 'upload/'.date('Ymd', time()).'/';
        //$folderName = 'upload/';
        $safeName = time() . uniqid() . '.' . $extension;
        $file->move($folderName, $safeName);
        return array('code' => 0, 'msg' => 'success', 'data' => $folderName . $safeName);//相对路径
    }

    //多图上传
    public static function uploadMultipleImages($request, $imgName)
    {
        $images = $request->file('images');
        $uploadedImages = [];

        foreach ($images as $image) {
            $path = $image->store('images', 'public');
            $uploadedImages[] = ['url' => Storage::url($path)];
        }

        return response()->json([
            'success' => true,
            'images' => $uploadedImages
        ]);
    }

    /**
     * 文件转base64输出
     * @param $filePath 文件路径
     */
    public static function getBase64ByPath($filePath)
    {
        if(!file_exists($filePath)){ return ''; }
        $mimeType = mime_content_type($filePath);
        $base64Data = base64_encode(file_get_contents($filePath));
        return 'data:'.$mimeType.';base64,'.$base64Data;
    }

    /**
     * 将Base64图片转换为本地图片并保存
     * @param  $base64 base64图片码
     */
    public static function getPathByBase64($base64)
    {
        $prefix = 'upload/'.date('Ymd', time()).'/';
        if(!file_exists($prefix)){ mkdir($prefix, 0777); }
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)){
            $type = $result[2];
            $prefix = $prefix . time() . uniqid() . '.' . $type;
            $resPut = file_put_contents($prefix, base64_decode(str_replace($result[1], '', $base64)));
            return $resPut ? $prefix : '';
        } else {
            $prefix = $prefix . time() . uniqid() . '.png';
            $resPut = file_put_contents($prefix, base64_decode($base64));
            return $resPut ? $prefix : '';
        }
    }

    /**
     * 切片上传视频
     */
    public static function uploadVideo($request, $num, $piece, $sjc)
    {
        if (!$request->hasFile('video')) {
            return array('code'=>-2,'msg'=>'没有视频上传');
        }
        $file = $request->file('video');
        $dir = 'upload/'.date('Ymd', time()).'/';
        if (!is_dir($dir)) {
            mkdir($dir, '0777', true);
        }
        $fileExt = $file->getClientOriginalExtension();
        $videoName = $sjc.'.'.$fileExt.'_'.$num; //分片名
        $file->move($dir, $videoName);
        $res = self::fileMerge($num,$piece,$dir,$sjc.'.'.$fileExt);
        if ($res['code']!=0) {
            return array('code'=>-2,'msg'=>$res['msg']);
        }
        $filePath = $res['data'];
        //删除分片
        for ($i=1; $i<=$piece; $i++) {
            unlink($dir.$sjc.'.'.$fileExt.'_'.$i);
        }
        return array('code'=>0,'msg'=>'success','data'=>$filePath);
    }

    //合并分片
    public static function fileMerge($num,$piece,$dir,$sjc)
    {
        if ($num!=$piece) {
            return array('code'=>-3,'msg'=>'还在上传中...');
        }
        $path = $dir.$sjc;
        for ($i=1; $i<=$piece; $i++) {
            $blob = file_get_contents($dir.$sjc.'_'.$i);
            $res = file_put_contents($path,$blob,FILE_APPEND | LOCK_EX);
            if (!$res) {
                return array('code'=>-2,'msg'=>'合并分片错误');
            }
        }
        return array('code'=>0,'msg'=>'success','data'=>$path);
    }

    /**
     * 压缩包上传
     * @return string
     */
    public static function uploadZip($request, $fileName = 'zip')
    {
        $uploadSizeLimit = 10 * 1024 * 1023; //限制上传文件尺寸10M
        $suffix_img = [ //允许后缀
            "zip", "rar",
        ];
        if (!$request->hasFile($fileName)) { return ''; }
        //判断文件存在
        if ($_FILES[$fileName]['size'] > $uploadSizeLimit) {
            //echo "<script>alert('图片过大！');history.go(-1);</script>";exit;
            return array('code'=>-2,'msg'=>'文件尺寸过大');
        }
        $file = $request->file($fileName);
        $data['fileSize'] = $file->getClientSize();
        if ($data['fileSize'] > $uploadSizeLimit) {
            return false;
        }
        $fileExt = $file->getClientOriginalExtension();
        $fileExt = strtolower($fileExt);
        if ($fileExt && !in_array($fileExt, $suffix_img)) {
            return array('code'=>-2,'msg'=>'文件类型不合法');
        }
        if(!$file->isValid()){
            return array('code'=>-2,'msg'=>'文件错误');
        }
        $extension = $fileExt ?: 'png';
        $folderName = 'upload/'.date('Ymd', time()).'/';
        $safeName = time() . uniqid() . '.' . $extension;
        $file->move($folderName, $safeName);
        return array('code' => 0, 'msg' => 'success', 'data' => $folderName . $safeName);//相对路径
    }
}